import re
import time

import scrapy

from ..demo import Kugou_Music
from ..items import AudioItem


class MusicSpider(scrapy.Spider,Kugou_Music):
    name = "music"
    # allowed_domains = ["www.kugou.com"]
    start_urls = ["https://www.kugou.com/yy/html/rank.html"]

    def parse(self, response):
        titles = response.xpath('//div[@class="pc_temp_side"]/div/ul/li/a/@title')
        rank_urls = response.xpath('//div[@class="pc_temp_side"]/div/ul/li/a/@href')
        ranks_list = {}
        for title, rank_url in zip(titles, rank_urls):
            title = title.extract()
            rank_url =rank_url.extract()
            ranks_list[title] = rank_url
        for i in ranks_list.keys():
            print(i,end='   ')
        print('\n')
        title = input('请输入需要下载的排行榜：')
        pages = int(input('请输入要下载的页数：'))
        for page in range(1,pages+1):
            temp_url = re.sub(r'(\d)-','%d-',ranks_list[title])
            print(temp_url % page)
            yield scrapy.Request(
                url = temp_url % page,
                callback = self.parse_music_id,
            )

    def parse_music_id(self,response):
        music_ids = re.findall(r'data-eid="(.*?)">', response.text)
        for music_id in music_ids:
            data_time = int(time.time()*1000)
            signature = self.signatureParam(data_time,music_id)
            base_url = 'https://wwwapi.kugou.com/play/songinfo'
            params = {
                'srcappid': '2919',
                'clientver': '20000',
                'clienttime': data_time,
                'mid': 'e0210972f895f3892d9c59ccbd509bf2',
                'uuid': 'e0210972f895f3892d9c59ccbd509bf2',
                'dfid': '11RSEY2CgLti0sA1Z92b6r4m',
                'appid': '1014',
                'platid': '4',
                'encode_album_audio_id': music_id,
                'token': '7fbb03ae5cec5b48d2a8be0818cdc923a69fa4aaba15945634f230ad10444724',
                'userid': '2159370610',
                'signature': signature,
            }
            data = []
            for k,v in params.items():
                data.append(f"{k}={v}")
            data = '&'.join(data)
            url = f"{base_url}?{data}"
            print(url)
            yield scrapy.Request(
                url=url,
                headers={'Referer': 'https://www.kugou.com/'},
                callback =self.parse_video_url,
            )

    def parse_video_url(self,response):
        res = response.json()
        item = AudioItem()
        item['url'] = res['data']['play_url']
        print(item['url'])
        item['name'] = res['data']['audio_name'] + '.mp3'
        item['author'] = res['data']['authors'][0]['author_name']
        yield item


